/**
 * created by lllwx
 * date: 2022/1/20
 * time: 5:31 下午
 * version: 1.0
 * desc 节流指令
 * 无配置调用方式 v-throttle="handleObjectEvent"
 * 配置参数节流调用 v-throttle="[handleObjectEvent, wait, event]"
 */
import Vue from 'vue';

Vue.directive('throttle', {
  bind(el, binding) {
    let fn = binding.value;
    let wait = 1000;
    let event = 'click';
    if (binding.value instanceof Array) {
      const [f, w, e] = binding.value;
      fn = f;
      wait && (wait = w);
      e && (event = e);
    }

    // el.lastTime 上次事件触发时间
    el.addEventListener(event, () => {
      const nowTime = new Date().getTime();
      if (!el.lastTime || nowTime - el.lastTime >= wait) {
        el.lastTime = nowTime;
        typeof fn === 'function' && fn();
      }
    });
  },
});
